package com.bishe.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bishe.entity.ScClass;
import com.bishe.entity.Score;
import com.bishe.entity.User;
import com.bishe.entity.resp.PageParam;
import com.bishe.entity.resp.R;
import com.bishe.exception.CommonException;
import com.bishe.service.ScClassService;
import com.bishe.service.ScoreService;
import com.bishe.service.UserService;
import io.swagger.annotations.Api;
import org.checkerframework.checker.units.qual.C;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (Score)表控制层
 *
 * @author makejava
 * @since 2024-04-03 23:24:50
 */
@RestController
@RequestMapping("score")
@Api(tags = "成绩信息控制器")
public class ScoreController {
    /**
     * 服务对象
     */
    @Resource
    private ScoreService scoreService;

    @Resource
    private ScClassService classService;

    @Resource
    private UserService userService;

    @GetMapping("synCJPM")
    public R synthesisRank() {
        List<User> users = userService
                .list(Wrappers.lambdaQuery(User.class)
                        .eq(User::getType, "s"));
        users.forEach(s -> {
            s.setIcon("123pm.png");
        });
        for (User user : users) {
            List<Score> scoreList = scoreService
                    .list(Wrappers.lambdaQuery(Score.class)
                            .eq(Score::getUid, user.getId()));
            if (CollUtil.isEmpty(scoreList)) {
                user.setResult(0);
            } else {
                int sum = scoreList.stream().mapToInt(Score::getResult).sum();
                user.setResult(sum);
            }
        }
        List<User> userList = users.stream()
                .sorted(Comparator.comparing(User::getResult,
                                Comparator.nullsFirst(Comparator.naturalOrder()))
                        .reversed())
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userList)) {
            if (ObjectUtil.isNotNull(userList.get(0))) {
                userList.get(0).setIcon("1pm.png");
            }
            if (userList.size() > 1 && ObjectUtil.isNotNull(userList.get(1))) {
                userList.get(1).setIcon("2pm.png");
            }
            if (userList.size() > 2 && ObjectUtil.isNotNull(userList.get(2))) {
                userList.get(2).setIcon("3pm.png");
            }
        }
        return R.data(userList);
    }


    @GetMapping("rank/{type}")
    public R rank(@PathVariable Integer type) {
        List<User> users = userService.list(Wrappers.lambdaQuery(User.class).eq(User::getType, "s"));
        for (User user : users) {
            ScClass byId = classService.getById(user.getStuClass());
            if (byId != null) {
                user.setStuClassName(byId.getGrade() + "-" + byId.getClassName());
            }

            List<Score> list = scoreService.list(Wrappers.lambdaQuery(Score.class)
                    .eq(Score::getUid, user.getId())
                    .eq(Score::getQualityId, type)
                    .orderByDesc(Score::getCjsj)
                    .last("limit 1"));
            if (list.isEmpty()) {
                user.setResult(0);
            } else {
                user.setResult(list.get(0).getResult());
            }
        }
        List<User> userList = users.stream()
                .sorted(Comparator.comparing(User::getResult, Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
                .collect(Collectors.toList());
        return R.data(userList);
    }


    @GetMapping("list")
    public R list() {
        List<Score> list = scoreService.list(Wrappers.lambdaQuery(Score.class).eq(Score::getUid, StpUtil.getLoginIdAsString()));
        Map<String, List<Score>> collect = list.stream().collect(Collectors.groupingBy(Score::getQualityId));
        return R.data(collect);
    }

    /**
     * 分页查询所有数据
     *
     * @return 所有数据
     */
    @PostMapping("page")
    public R selectAll(@RequestBody PageParam pageParam) {
        return R.data(this.scoreService.page(pageParam));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return R.data(this.scoreService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param score 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody Score score) {
        Score one = scoreService.getOne(Wrappers.lambdaQuery(Score.class).eq(Score::getUid, score.getUid()).eq(Score::getQualityId, score.getQualityId()));
        if (one != null) {
            throw new CommonException("该学生已评论 " + score.getQualityName() + " 类目");
        }

        score.setTid(StpUtil.getLoginIdAsString());
        score.setCjsj(new Date());
        return R.data(this.scoreService.save(score));
    }

    /**
     * 修改数据
     *
     * @param score 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody Score score) {
        return R.data(this.scoreService.updateById(score));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam("idList") List<Long> idList) {
        return R.data(this.scoreService.removeByIds(idList));
    }
}

